package com.king.login.service.impl;

import com.king.login.entity.SystemUser;
import com.king.login.security.LoginUser;
import com.king.login.service.LoginService;
import com.king.platform.enmu.ResultEnum;
import com.king.platform.entity.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
  @Autowired
  AuthenticationManager authenticationManager;

  @Override
  public BaseResult login(SystemUser systemUser) {
    Map<String, Object> result = new HashMap<>();
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(systemUser.getUserName(), systemUser.getPassword());
    Authentication authenticate = authenticationManager.authenticate(auth);
    if (Objects.isNull(authenticate)) {
      throw new RuntimeException("登录失败");
    }

    LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
    return BaseResult.success(ResultEnum.SUCCESS_CODE, result);
  }
}
